import mongoose from 'mongoose';

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    trim: true,
    maxlength: 8 // 用户名限制不超过8个字符
  },
  account: {
    type: String,
    required: true,
    unique: true,
    trim: true,
    match: /^[0-9]{8,12}$/,
    minlength: 8,
    maxlength: 12
  },
  email: {
    type: String,
    required: true,
    unique: true,
    trim: true,
    lowercase: true
  },
  phone: {
    type: String,
    trim: true
  },
  password: {
    type: String,
    required: true,
    minlength: 8,
    maxlength: 60
    // 密码验证将在控制器中处理，哈希后长度约为60字符
  },
  avatar: {
    type: String,
    default: 'src/assets/avatars/Scorpio.png'
  },
  gender: {
    type: String,
    enum: ['male', 'female', 'unknown'],
    default: 'unknown'
  },
  birth: {
    type: Date
  }
}, {
  timestamps: true
});

// 虚拟字段，不存储在数据库中
userSchema.virtual('id').get(function() {
  return this._id.toHexString();
});

// 确保JSON序列化时包含virtual字段
userSchema.set('toJSON', {
  virtuals: true,
  versionKey: false,
  transform: function(doc, ret) {
    // 删除密码字段，不返回给客户端
    delete ret.password;
  }
});

const User = mongoose.model('User', userSchema);

export default User;